// 处理进程通讯

const { ipcMain } = require("electron");
const { send: sendMainWindow } = require("./windows/main");
const {
  create: createControlWindow,
  send: sendControlWindow,
} = require("./windows/control");
const signal = require("./signal");

module.exports = function () {
  // 控制端主进程处理渲染进程的 login
  // 然后产生一个 6 位的本机控制码
  ipcMain.handle("login", async () => {
    let { code } = await signal.invoke("login", null, "logined");
    return code;
  });

  // 控制端主进程监听渲染进程里触发的 control 事件
  ipcMain.on("control", async (e, remote) => {
    signal.send("control", { remote });
  });

  signal.on("controlled", (data) => {
    createControlWindow();
    sendMainWindow("control-state-change", data.remote, 1);
  });

  signal.on("be-controlled", (data) => {
    sendMainWindow("control-state-change", data.remote, 2);
  });

  ipcMain.on("forward", (e, event, data) => {
    signal.send("forward", { event, data });
  });

  signal.on("offer", (data) => {
    sendMainWindow("offer", data);
  });

  signal.on("answer", (data) => {
    sendControlWindow("answer", data);
  });

  signal.on("puppet-candidate", (data) => {
    sendControlWindow("candidate", data);
  });

  signal.on("control-candidate", (data) => {
    sendMainWindow("candidate", data);
  });
};
